import _ from 'lodash-es';
import { defineStore } from 'pinia';
import { getSystemDeptAll, getSystemPermissionAll, getSystemRoleAll } from '@/apis/api-system';

const useSystemStore = defineStore('storeSystem', {
  state: () => ({
    systemMenu: [], // 系统菜单
    systemDept: [], //组织数据
    systemRole: [], //系统所有角色
    systemPermission: [], //系统所有权限
    personalShow: false, //个人中心显示
  }),

  actions: {
    // 存储个人中心显示状态
    SET_PERSONAL_SHOW(show) {
      this.personalShow = show;
    },
    // 存储系统所有权限
    STORE_SYSTEM_PERMISSION(permission) {
      this.systemPermission = permission;
    },
    // 存储系统所有角色
    STORE_SYSTEM_ROLE(role) {
      this.systemRole = role;
    },

    // 存储部门信息
    STORE_SYSTEM_DEPT(dept) {
      this.systemDept = dept;
    },

    // 存储系统菜单
    STORE_SYSTEM_MENU(menu) {
      this.systemMenu = menu;
    },

    // 树形结构转换成一维数组
    getOneArr(arr) {
      let tree = _.cloneDeep(arr);
      let newData = {};

      const expanded = (datas) => {
        if (datas && datas.length > 0) {
          datas.forEach((e) => {
            newData[e.title] = false;
            expanded(e.children);
          });
        }
      };

      expanded(tree);
      this.STORE_SYSTEM_PERMISSION(newData);
    },

    // 获取所有菜单
    async getSystemPermissionAllApi() {
      try {
        const [err, data] = await getSystemPermissionAll();

        if (!err) {
          this.STORE_SYSTEM_MENU(data.data);

          this.getOneArr(data.data);
        }
      } catch (error) {
        return Promise.reject(error);
      }
    },

    // 获取所有组织架构
    async getSystemDeptAllApi() {
      try {
        const [err, data] = await getSystemDeptAll();

        if (!err) {
          this.STORE_SYSTEM_DEPT(data.data);
        }
      } catch (error) {
        return Promise.reject(error);
      }
    },
    // 获取所有角色
    async getSystemRoleAllApi() {
      try {
        const [err, data] = await getSystemRoleAll();

        if (!err) {
          this.STORE_SYSTEM_ROLE(data.data);
        }
      } catch (error) {
        return Promise.reject(error);
      }
    },
  },
});

export default useSystemStore;
